from google.appengine.ext import webapp
from log_cat import log_utils
import logging

img_file_name = 'assets/ubuntu_2_s.jpg'
font_file_name = 'assets/verdana.ttf'

class JPGClientHandler(webapp.RequestHandler):
    def get(self):
        pil_enabled = False
        try:
            from PIL import Image, ImageFont, ImageDraw
            pil_enabled = True
        except Exception, msg:
            logging.debug(msg)
            pil_enabled = False
        try:
            log_utils.log2db(self.request)
            self.response.headers['Cache-Control'] = 'no-cache'
            self.response.headers['Content-Type'] = 'image/jpeg'
            if(pil_enabled):
                img = Image.open(img_file_name)
                draw = ImageDraw.Draw(img)
                font = ImageFont.truetype(font_file_name, 14)
                clientInfo = log_utils.getClientInfo(self.request)
                tmp_h = font.getsize('j')[1] + 1
                img_w = img.size[0]
                img_h = img.size[1]
                tmp_y = (img_h - tmp_h*len(clientInfo))/2
                for info_item in clientInfo:
                    tmp_w = font.getsize(info_item)[0]
                    tmp_x = (img_w-tmp_w)/2
                    if(tmp_x<0):
                        tmp_x = 0
                    draw.text((tmp_x, tmp_y), info_item, font=font)
                    tmp_y = tmp_y + tmp_h
                del draw
                img.save(self.response.out, 'JPEG')
            else:
                img_file = open(img_file_name, 'rb')
                for img_data in img_file:
                    self.response.out.write(img_data)
                img_file.close()
        except Exception, msg:
            logging.error(msg)
    
    def post(self):
        get(self)